import { reactive, watchPostEffect } from 'vue'
import { useRoute } from 'vue-router'

export interface MenuTree {
  title: string
  href: string
  children: MenuTree[]
}

const generateNavLinkList = (ListEls: NodeListOf<HTMLElement> | HTMLElement[]): MenuTree[] => {
  if (ListEls.length === 0) return []

  const linkList: MenuTree[] = []

  for (const item of ListEls) {
    const menu: MenuTree = {
      href: new URL(item?.querySelector('a')?.href ?? '').hash,
      title: item?.querySelector('a')?.text.trim() ?? '',
      children: []
    }
    menu.children = generateNavLinkList(item.querySelectorAll('ol > li'))
    linkList.push(menu)
  }

  return linkList
}

/** @Todo 编写 markdown-it 插件在构建时获取目录信息并绑定到 globalThis */
export function useArticleToc() {
  const menuTree = reactive<MenuTree[]>([])

  const buildLinkList = () => {
    const ListEls = document.querySelectorAll('#markdown-toc > ol > li') as NodeListOf<HTMLElement>
    menuTree.push(...generateNavLinkList(ListEls))
  }

  const route = useRoute()
  watchPostEffect((onClean) => {
    /** 路由更新后重新渲染目录 */
    if (route.fullPath) {
      onClean(() => (menuTree.length = 0))
      buildLinkList()
    }
  })

  return {
    menuTree
  }
}
